//
//  HMNetworkTools.m
//  OC封装网络工具类
//
//  Created by heima on 16/8/30.
//  Copyright © 2016年 heima. All rights reserved.
//

#import "DMWNetworkTools.h"

@protocol DMWNetworkToolsDelegate <NSObject>

@optional
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;

@end

@interface DMWNetworkTools()<DMWNetworkToolsDelegate>

@end

@implementation DMWNetworkTools

+ (instancetype)sharedTools {
    static dispatch_once_t onceToken;
    static DMWNetworkTools *instance;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        // 设置当前 instance 的可接受类型
        instance.responseSerializer.acceptableContentTypes = [instance.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    });
    return instance;
}

// 方式3
- (void)request:(HMHttpMethod)method urlString:(NSString *)urlString parameters:(id)parameters completion:(void(^)(id response, NSError *error))completion{
    
    // 请求成功的block
    void(^successBlock)(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) = ^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 请求成功
        completion(responseObject, nil);
    };
    
    // 请求失败的block
    void(^failureBlock)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) = ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        completion(nil, error);
    };
    
    NSString *m = method == HMHttpMethodGet ? @"GET" : @"POST";
    [[self dataTaskWithHTTPMethod:m URLString:urlString parameters:parameters uploadProgress:nil downloadProgress:nil success:successBlock failure:failureBlock] resume];
     
}






@end
